﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

/// <summary>
/// Class1 的摘要说明
/// </summary>
/// 
namespace com.baidu.ai
{
    public class ToBase64
    {
        public static string ImgToBase64String(string Imagefilename)
        {
            //try
            //{
            //Bitmap bmp = new Bitmap(Imagefilename);
            //MemoryStream ms = new MemoryStream();
            //bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            //byte[] arr = new byte[ms.Length];
            //ms.Position = 0;
            //ms.Read(arr, 0, (int)ms.Length);
            //ms.Close();
            //string temp= Convert.ToBase64String(arr);
            //return HttpUtility.UrlEncode(temp);
            //}
            //catch (Exception ex)
            //{
            //
            //    return null;
            //}



            //string urlStr = System.Web.HttpUtility.UrlEncode(Imagefilename);
            //string encode = "";
            //byte[] bytes = (Encoding.UTF8.GetBytes(urlStr));//encodeType.GetBytes(source);
            //try
            //{
            //    encode = Convert.ToBase64String(bytes);
            //}
            //catch
            //{
            //    encode = urlStr;
            //}
            ////return encode;
            //return urlStr;
            ////string base64Str = Base64Encode(urlStr);

            MemoryStream ms = new MemoryStream();
            try
            {
                Bitmap bmp = new Bitmap(Imagefilename);
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                //Log.WriteLog4Ex("图片转base64", ex);
                return "";
            }
            finally
            {
                ms.Close();
            }
            
        }

    }
}